<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sign In</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
</head>

<body>
  <h2>Sign In</h2>
  <form>
    <label for="">
      用户名:
      <input type="text" name="username">
    </label>
    <label for="">
      密码:
      <input type="text" name="password">
    </label>
    <button>Sign In</button>
  </form>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      // 创建 axios 实例
      const instance = axios.create({
        baseURL: 'http://127.0.0.1',
        timeout: 10000,
      })

      // 请求拦截器
      instance.interceptors.request.use(function (config) {
        // 进度条开始
        NProgress.start();
        return config;
      })

      // 响应拦截器
      instance.interceptors.response.use(function (res) {
        // 进度条结束
        NProgress.done();
        const { data } = res
        // 判读响应成功返回的结果
        if (data.code !== 100) {  // 结果不是预期
          return Promise.reject(data)
        }
        return data
      })

      // 获取节点
      const oForm = document.querySelector('form')
      oForm.onsubmit = async function (e) {
        // 阻止事件默认行为
        e.preventDefault()
        const target = e.target

        // 发送请求
        const data = {
          username: target[0].value,
          password: target[1].value
        }
        try {
          const result = await instance.post('/signIn', data, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          handler(result)
        } catch (error) {
          alert(error.msg)
        }

        // return false // 阻止事件默认行为(异步无法使用)
      }

      function handler({data}) {
        // 将 token 存入 local storage
        console.log(data.token)
        localStorage.setItem('token', data.token)
        // 跳转页面
        location.href = '/6.22/跨域/CORS//axios.html'
      }
    })
  </script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</body>

</html>